import { _decorator, Component, Node, randomRange, tween, UITransform, Vec3 } from 'cc';
import { SunManager } from './manager/SunManager';
import { SunFlower } from './SunFlower';
import { AudioManager } from './manager/AudioManager';
import { Config } from './manager/Config';
const { ccclass, property } = _decorator;

@ccclass('Sun')
export class Sun extends Component {
    @property(Number)
    point: number = 0;
    protected onLoad(): void {
        this.node.on(Node.EventType.MOUSE_DOWN,this.onMouseDown, this);
    }
    protected onDestroy(): void {
        this.node.off(Node.EventType.MOUSE_DOWN,this.onMouseDown, this);
    }

    /**
     * 线性移动到目标点
     */
    linearTo(SunNodex:number){
        tween(this.node)
            // 将当前节点位置动画移动到中间节点位置
            .to(3, { position: new Vec3(SunNodex, randomRange(230,-300), 0) }, { easing: 'linear' })
             // 启动动画
            .start();
    }
    /**
     * 弹性移动到目标点
     */
    jumpTo() {
        // 获取当前节点的位置
        let startPos = this.node.position;
        // 获取中间节点的位置
        let middlePos = startPos.clone().add(new Vec3(0, randomRange(20, 70), 0));
        // 获取目标节点的位置
        let targetPos = startPos.clone().add(new Vec3(randomRange(-70, 70), 0, 0));

        tween(this.node)
            // 将当前节点位置动画移动到中间节点位置
            .to(0.5, { position: middlePos }, { easing: 'sineOut' })
            // 将当前节点位置动画移动到目标节点位置
            .to(0.5, { position: targetPos }, { easing: 'sineIn' })
            // 启动动画
            .start();
    }
    //鼠标按下事件
    onMouseDown() {
        //获取目标节点的世界坐标
        let targetWorldPos = SunManager.Instance.sunPointLabel.node.getComponent(UITransform).convertToWorldSpaceAR(new Vec3(0, 0, 0));
        //将目标结点的世界坐标转换为当前节点(this.node)的父节点的本地坐标
        let targetLocalPos=this.node.parent.getComponent(UITransform).convertToNodeSpaceAR(targetWorldPos);
        tween(this.node) 
            .to(1, { position: targetLocalPos})
            .call(() => {
                AudioManager.Instance.playClip(Config.sunpoint);
                SunManager.Instance.addSun(this.point);
                this.node.destroy();
            })
            .start();
    }
}


